import ScrollBarLayout from '@/components/ScrollBarLayout';
import Cls from 'classnames';
import { useContext, useEffect, useMemo, useState } from 'react';
import { INeedActionEnum, NeedControllerContext } from '../common';
import { Button, Table, message } from 'antd';
import { getOATableColumns } from '../mconfig/OATableColumns';
import { NeedManageAPI } from '../common/type';
import { JHXD_STATE, JZLZ_STATE, KCBSH_STATE, purchaseNeedCategory, SHZ_STATE, ZRBGH_STATE } from '../common/Format';
import lodash from 'lodash';
import moment from 'moment';
import { BZZ_CHECKSTATE, SHTG_CHECKSTATE } from '../../Acommon';
import { CloudUploadOutlined, MenuUnfoldOutlined } from '@ant-design/icons';
import { UpdateNeedMaterialBatchUpload } from '../mview/UpdateNeedMaterialBatchUpload';
import { AuditModal } from '../mview/AuditModal';
import { addPlanServices, syncPDFtoOAServices } from '../services/UpdateService';
import _ from 'lodash';
export const DetailInfoCenterViewMainOA: React.FC = () => {
  /** 获取上下文 */
  const { styleFixCls, curRes, needDetailInfo, needForm, reloadDetail, needDispatch, tableData, nodesFlowListMemo, NumGatherMemo } = useContext(
    NeedControllerContext,
  );

  const [flag, setFlag] = useState(false); /**是否调用生成计划和同步PDF接口*/
  const [tableKeys, setTableKeys] = useState<any[]>([]); // 表格多选的key值保存
  const [batchModal, setBatchModal] = useState<Record<string, any>>({
    // 批量上传弹窗开关
    isShow: false,
    resObj: null,
  });
  const [isShowAudit, setIsShowAudit] = useState<Record<string, any>>({
    //是否显示审核弹窗
    isShow: false,
    selectId: '',
    type: '',
    planInfo: {},
    way: '',
  });

  // table表格的选择框是否显示
  const rowSelectionMemo = useMemo(() => {
    if (needDetailInfo?.state && needDetailInfo?.state == JZLZ_STATE() && needDetailInfo?.checkState == BZZ_CHECKSTATE() && nodesFlowListMemo) {
      return {
        type: 'checkbox',
        onChange: (val: any[]) => {
          setTableKeys(val);
        },
      };
    } else if (needDetailInfo?.state && needDetailInfo?.state == ZRBGH_STATE() && needDetailInfo?.checkState == BZZ_CHECKSTATE() && nodesFlowListMemo) {
      return {
        type: 'checkbox',
        onChange: (val: any[]) => {
          setTableKeys(val);
        },
        getCheckboxProps: (record) => ({
          disabled: Number(record?.expectSum) < 1000000,
        }),
      };
    } else {
      return undefined;
    }
  }, [needDetailInfo?.state, nodesFlowListMemo, needDetailInfo?.checkState]);

  /** 表格编辑方法 */
  const onEditTable = ({ value, type, key, record }: Record<string, any>) => {
    const index = tableData.findIndex((item: Record<string, any>) => item.id == record.id);
    const currentData = lodash.cloneDeep(tableData);
    if (type == 'switch') {
      /**改变switch的值*/
      currentData[index][key] = Number(value);
      /**如果是关闭switch那么将url清空*/
      if (key === 'needProofFlag') {
        //需求论证
        if (!value) {
          currentData[index]['needProofURL'] = null;
        }
      } else if (key === 'needImportFlag') {
        //进口
        if (!value) {
          currentData[index]['needImportURL'] = null;
        }
      } else if (key === 'needSingleFlag') {
        //单一来源
        if (!value) {
          currentData[index]['needSingleURL'] = null;
        }
      }
    } else if (type == 'InputNumber') {
      // 修改表格数量。重新计算预告总价
      if (key == 'expectNum') {
        currentData[index].expectNum = value;
        currentData[index].expectSum = ((value as number) * record.expectPrice).toFixed(2);
      }
      // 修改表格预估单价。重新计算预告总价
      if (key == 'expectPrice') {
        currentData[index].expectPrice = value;
        currentData[index].expectSum = ((value as number) * record.expectNum).toFixed(2);
      }
    } else if (type == 'TimePicker') {
      currentData[index][key] = value ? moment(value as any).format('YYYY-MM-DD HH:mm:ss') : null;
    } else if (type == 'UploadFormCommon') {
      // 上传文件
      currentData[index][key] = value;
    }
    // setDataSource(currentData);
    needDispatch({
      type: INeedActionEnum.SET_tableData,
      payload: currentData,
    });
  };

  // 表格方法
  const operateFuns = {
    onAudit: (record: Record<string, any>, value: string) => {
      //onAudit(点击审核事件)
      setIsShowAudit({
        isShow: true,
        selectId: record?.id,
        type: 'radio',
        planInfo: needDetailInfo,
        way: value,
      });
    },
  };

  /** Table的columns集合 */
  const getTableColumn: Record<string, any>[] = useMemo(() => {
    return getOATableColumns(needForm, needDetailInfo, nodesFlowListMemo, onEditTable, operateFuns);
  }, [curRes, tableData, needDetailInfo, nodesFlowListMemo]);

  /** 是否显示【批量审核button】和多选框【checkbox】 */
  const isShowAuditMemo = useMemo(() => {
    return needDetailInfo?.state && needDetailInfo?.state == ZRBGH_STATE() && needDetailInfo?.checkState == BZZ_CHECKSTATE() && nodesFlowListMemo;
  }, [needDetailInfo?.state, needDetailInfo?.checkState, nodesFlowListMemo]);

  /** 批量审核方法 */
  const batchAudit = () => {
    if (tableKeys?.length >= 1) {
      setIsShowAudit({
        isShow: true,
        selectId: tableKeys?.toString(),
        type: 'checkBox',
        planInfo: needDetailInfo,
        way: '',
      });
    } else {
      message.warning('请选择物料！');
    }
  };

  useEffect(() => {
    let newarr = _?.cloneDeep(needDetailInfo?.purchaseNeedMaterials);
    newarr?.forEach((item) => {
      let needProofFlag = 0;
      if (Number(item?.expectSum) >= 500000) {
        needProofFlag = 1;
      }
      item.needProofFlag = needProofFlag;
    });
    needDispatch({
      type: INeedActionEnum.SET_tableData,
      payload: newarr,
    });
  }, [needDetailInfo?.purchaseNeedMaterials]);

  /** 同步审核记录给档案 */
  const { syncPDFtoOARun, syncPDFtoOALoading } = syncPDFtoOAServices((res) => {});
  const syncPDFtoOARunfun = (infoObj) => {
    //需要调用同步接口
    let mactivitiHisTaskInstList = infoObj?.paramObject?.[purchaseNeedCategory()]?.mactivitiHisProcinstList?.[0]?.mactivitiHisTaskInstList;
    let resObj = { ...infoObj, paramObject: { mactivitiHisTaskInstList } };
    syncPDFtoOARun(resObj);
  };

  /** 添加计划serivces */
  const { addPlanRun, addPlanLoading } = addPlanServices((res) => {
    if (res?.msgFlag) {
      message?.success(res?.msg);
    }
  });

  /**
   * 监听状态，执行计划下达和同步档案
   * */
  useEffect(() => {
    if (needDetailInfo?.state == KCBSH_STATE() || needDetailInfo?.state == SHZ_STATE()) {
      setFlag(true);
    }
    if (needDetailInfo?.state == JHXD_STATE() && flag) {
      if (!needDetailInfo?.purchasePlan?.id) {
        /** 计算通过的物料总价 */
        let allExpectSum = 0;
        needDetailInfo?.purchaseNeedMaterials?.forEach((item) => {
          if (item?.checkState == 1) {
            allExpectSum += Number(item?.expectSum);
          }
        });

        /** 调添加到计划的接口 */
        let addPlanData = {
          supplyWay: needDetailInfo?.supplyWay,
          supplyKind: needDetailInfo?.supplyKind,
          planName: needDetailInfo?.needName?.replace('需求', '计划'), //数据进入计划管理，将后缀改成计划管理
          planInfo: needDetailInfo?.needDetailInfo,
          expectSum: allExpectSum,
          state: '0',
          // <<<========================================>>>
          applyCompanyID: needDetailInfo?.applyCompanyID,
          applyCompanyName: needDetailInfo?.applyCompanyName,
          applyDepartmentID: needDetailInfo?.applyDepartmentID,
          applyDepartmentName: needDetailInfo?.applyDepartmentName,
          applyPositionID: needDetailInfo?.applyPositionID,
          applyPositionName: needDetailInfo?.applyPositionName,
          applyerID: needDetailInfo?.applyerID,
          applyerName: needDetailInfo?.applyerName,
          applyTime: needDetailInfo?.applyTime,
          ownCompanyID: needDetailInfo?.ownCompanyID,
          ownCompanyName: needDetailInfo?.ownCompanyName,
          ownDepartmentID: needDetailInfo?.ownDepartmentID,
          ownDepartmentName: needDetailInfo?.ownDepartmentName,
          ownPhone: needDetailInfo?.ownPhone, // 联系电话
          ownPositionID: needDetailInfo?.ownPositionID,
          ownPositionName: needDetailInfo?.ownPositionName,
          ownTime: needDetailInfo?.ownTime,
          ownerID: needDetailInfo?.ownerID,
          ownerName: needDetailInfo?.ownerName, // 联系人
          // <<<========================================>>>
          mpurchaseNeeds: [{ id: needDetailInfo?.id }],
          purchaseNeedMaterials: needDetailInfo?.purchaseNeedMaterials?.map((item) => {
            return { id: item?.id };
          }),
        };
        addPlanRun(addPlanData);
        syncPDFtoOARunfun(needDetailInfo);
      }
    }
  }, [needDetailInfo?.state, needDetailInfo?.checkState]);

  return (
    <>
      <div className="commonTabsBodyDom">
        <div className={Cls('tabsBodyInfoDom', `${styleFixCls}updateFormBox`)}>
          <ScrollBarLayout style={{ padding: '5px 100px', display: 'flex', flexDirection: 'column' }}>
            <div className={`${styleFixCls}infoViewOA-centerBodyTitleBox`}>{needDetailInfo?.needName}</div>
            {needDetailInfo?.state && needDetailInfo?.state == JZLZ_STATE() && nodesFlowListMemo && needDetailInfo?.checkState == BZZ_CHECKSTATE() ? (
              // &&
              // !isView
              <div style={{ margin: '0.5rem 1rem' }}>
                <Button
                  type="primary"
                  // icon={<CloudUploadOutlined />}
                  onClick={() => {
                    if (tableKeys?.length) {
                      setBatchModal({
                        isShow: true,
                        resObj: tableKeys,
                      });
                    } else {
                      message?.warning('请至少选择一个标的');
                    }
                  }}
                >
                  批量上传
                </Button>
              </div>
            ) : null}
            {isShowAuditMemo && curRes?.['/purchaseNeedMaterialController/check'] && (
              <div style={{ display: 'flex', justifyContent: 'space-between', margin: '0.2rem 1rem' }}>
                <div style={{ display: 'flex' }}>
                  <Button
                    type="primary"
                    // icon={<MenuUnfoldOutlined />}
                    style={{}}
                    onClick={batchAudit}
                  >
                    批量操作
                  </Button>
                  <div style={{ lineHeight: '35px', marginLeft: '10px' }}>
                    已选择&nbsp;
                    <span style={{ color: '#1677ff', fontWeight: '700' }}>{tableKeys?.length}</span>
                    &nbsp;个物料
                  </div>
                </div>
                <div style={{ display: 'flex', lineHeight: '35px' }}>
                  <div>
                    已审核&nbsp;
                    <span style={{ color: '#1677ff', fontWeight: '700' }}>{NumGatherMemo?.yiNum}</span>
                    &nbsp;个物料
                  </div>
                  <div style={{ marginLeft: '10px' }}>/</div>
                  <div style={{ marginLeft: '10px' }}>
                    待审核&nbsp;
                    <span style={{ color: '#1677ff', fontWeight: '700' }}>{NumGatherMemo?.daiNum}</span>
                    &nbsp;个物料
                  </div>
                </div>
              </div>
            )}
            <div className="list-table">
              <Table
                dataSource={tableData}
                scroll={{ x: 'true', y: 'true' }}
                pagination={false}
                rowSelection={rowSelectionMemo as Record<string, any>}
                size={'small'}
                columns={getTableColumn}
                bordered
                rowKey={'id'}
              />
            </div>
          </ScrollBarLayout>
        </div>
      </div>
      {/* 业务审核物料弹窗 */}
      {isShowAudit?.isShow && (
        <AuditModal
          isShowAudit={isShowAudit}
          onClose={() => setIsShowAudit({})}
          getPlanInfo={() => {
            reloadDetail();
            setTableKeys([]);
          }}
        />
      )}
      {/* 批量上传弹窗 */}
      {batchModal?.isShow && (
        <UpdateNeedMaterialBatchUpload
          status={batchModal}
          onClose={() => {
            setBatchModal({
              isShow: false,
              resObj: null,
            });
          }}
          onSave={(resObj) => {
            /** 遍历数据,判断如果选择了是，那么url是否上传，没有上传则需要提示！ */
            const newarr = tableData?.map((item) => {
              const newObj = { ...item };
              if (tableKeys?.indexOf(item?.id) != -1) {
                // 判断有没有需求论证意见url返回 && 当预估总价大于50w的时候才允许上传需求论证意见
                if (resObj?.['needProofURL'] && !(Number(newObj?.expectSum) < 500000)) {
                  newObj.needProofFlag = 1;
                  newObj.needProofURL = resObj?.['needProofURL'];
                }
                // 判断有没有进口专业人员论证意见url返回 &&  当选择是进口，才能上传专业人员论证意见
                if (resObj?.['needImportURL'] && Boolean(newObj?.importFlag)) {
                  newObj.needImportFlag = 1;
                  newObj.needImportURL = resObj?.['needImportURL'];
                }
                // 判断有没有单一来源论证意见url返回 && 当选择了单一来源，才能上传单一来源论证意见
                if (resObj?.['needSingleURL'] && Boolean(newObj?.singleFlag)) {
                  newObj.needSingleFlag = 1;
                  newObj.needSingleURL = resObj?.['needSingleURL'];
                }
              }
              return newObj;
            });

            /**
             * 数据抛出
             * */
            needDispatch({
              type: INeedActionEnum.SET_tableData,
              payload: newarr,
            });
          }}
        />
      )}
    </>
  );
};
